/* Some jQuery calls for the food system 
*/	
$(document).ready(function() {
        /* Some variables for the profile form */
        var name = $( "#name" ),
	    birthyear = $( "#birthyear" ),
	    height = $( "#height" ),
            lossprofile = $( "#lossprofile" ),
            gender = $( "#gender" ),
            activitylevel = $( "#activitylevel" ),
            calculateneed = $( "#calculateneed" ),
            caloricneed = $( "#caloricneed" ),
        
            /* all fields that require validation */
	    allFields = $( [] ).add( name ).add( birthyear ).add( height ).add( caloricneed ),
            tips = $( ".validateTips" );

        $("#usermenu").hide();
        $("#usernick").click(function(e){
          // stop normal link click
          e.preventDefault();
          // show the div.
          $("#usermenu").slideDown();
          e.stopPropagation();
        });
        

	$("#userprofile").click(function(e){
	  // stop normal link click
	  e.preventDefault();
	  $( "#dialog-form" ).dialog( "open" );
          updateTips( "All fields are required");

          // set some sort of loading indicator...
          
          $.getJSON("/jsonrpc?action=GetProfile",
                    {},
                    function f(data) {
                      if ( data.error ) {
                        updateTips( data.error );
                        $("#pstatus").html( dump( data ) );
                      }
                      else {
                        // Fill the data into the dialogs form fields.
                        $("#name").val( data.name );
                        $("#birthyear").val( data.birthyear );
                        $("#height").val( data.height );
                        $("#caloricneed").val( data.caloricneed );
                        $("#gender").val( data.gender );
                        $("#calculateneed").attr( "checked", data.calculateneed );
                        $("#lossprofile").val( data.lossprofile );
                        $("#activitylevel").val( data.activitylevel );
                      }
                    });

          // clear the loading indicator...
	});


        $( "#dialog-form" ).dialog({
			autoOpen: false,
			height: 600,
			width: 350,
			modal: true,
			buttons: {
			  "Update": function() {
				  var bValid = true;
				  allFields.removeClass( "ui-state-error" );
                                  
				  bValid = bValid && checkLength( name, "name", 3, 16 );

				  bValid = bValid && checkRegexp( name, /^[a-zA-Z]([0-9a-zA-Z ])+$/i, "Name may consist of a-z, A-Z, 0-9, spaces." );
                                  bValid = bValid && checkRegexp( birthyear, /^[0-9]{4}$/, "Birthyear can only contain digits and must be 4 digits long." );
                                  bValid = bValid && checkRegexp( height, /^[0-9]{3}$/, "Height can only contain digits and must be 3 digits long." );
                                  if ( calculateneed == false ) {
                                    bValid = bValid && checkRegexp( caloricneed, /^[0-9]+{3,4}$/, "Caloric need must be numeric and between 100 and 9999" );
                                  }

				  if ( bValid ) {
                                    /* send profile information toserver */
                                    var rpcdata = {};
                                    rpcdata["name"] = name.val();
				    rpcdata["birthyear"] = birthyear.val();
				    rpcdata["height"] = height.val();
				    rpcdata["caloricneed"] = caloricneed.val();
                                    if ( calculateneed.val() == "on" ) {
                                      rpcdata["calculateneed"] = "true";
				    }
                                    else {
                                      rpcdata["calculateneed"] = "false";
				    }
				    rpcdata["gender"] = gender.val();
				    rpcdata["lossprofile"] = lossprofile.val();
				    rpcdata["activitylevel"] = activitylevel.val();
				    $( this ).dialog( "close" );
                                    $.getJSON("/jsonrpc?action=StoreProfile",
                                              rpcdata,
                                              function(data) {
                                                if ( data.error ) {
                                                  $("#pstatus").html( dump( data ) );
                                                }
                                              });
                                  }
				},
			  Cancel: function() {
			    $( this ).dialog( "close" );
			  }
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
	
	
	/* The "click anywhere to clear profile menu" functionality */
	$(document).click(function(e){
		$("#usermenu").hide();
	});
 	
	
        function updateTips( t ) {
            tips
                .text( t )
                .addClass( "ui-state-highlight" );
            setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
            }, 500 );
        }

        function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass( "ui-state-error" );
                if ( min == max ) {
                    updateTips( "Length of " + n + " must be exactly " + min + " characters in length." );
                }
                else {
                    updateTips( "Length of " + n + " must be between " + min + " and " + max + "." );
                }
                return false;
            } else {
                return true;
            }
        }

        function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                updateTips( n );
                return false;
            } else {
                return true;
            }
        }
		
});


function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function Request(function_name, opt_argv) {


  // If optional arguments was not provided, create it as empty
  if (!opt_argv)
    opt_argv = new Array();

  // Find if the last arg is a callback function; save it
  var callback = null;
  var len = opt_argv.length;
  if (len > 0 && typeof opt_argv[len-1] == 'function') {
    callback = opt_argv[len-1];
    opt_argv.length--;
  }
  var async = (callback != null);

  // Encode the arguments in to a URI
  var query = 'action=' + encodeURIComponent(function_name);
  for (var i = 0; i < opt_argv.length; i++) {
    var key = 'arg' + i;
    var val = JSON.stringify(opt_argv[i]);
    query += '&' + key + '=' + encodeURIComponent(val);
  }
  query += '&time=' + new Date().getTime(); // IE cache workaround

  // See http://en.wikipedia.org/wiki/XMLHttpRequest to make this cross-browser compatible
  var req = new XMLHttpRequest();

  // Create a 'GET' request w/ an optional callback handler
  req.open('GET', '/jsonrpc?' + query, async);

  if (async) {
    req.onreadystatechange = function() {
      if(req.readyState == 4 && req.status == 200) {
        var response = null;
        try {
         response = JSON.parse(req.responseText);
        } catch (e) {
         response = req.responseText;
        }
        callback(response);
      }
    }
  }

  // Make the actual request
  req.send(null);
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}



